package com.ywjt.platformbusiness.market.seckillgoods.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.constants.Constants;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.market.hagglegoods.activity.HaggleGoodsDetail;
import com.ywjt.platformbusiness.market.hagglegoods.activity.HaggleMallActivity;
import com.ywjt.platformbusiness.market.hagglegoods.adapter.HaggleGoodsAdapter;
import com.ywjt.platformbusiness.market.hagglegoods.model.GroupListModel;
import com.ywjt.platformbusiness.market.seckillgoods.adapter.SeckillGoodsAdapter;
import com.ywjt.platformbusiness.market.seckillgoods.model.SeckillGoodsListModel;
import com.ywjt.platformbusiness.util.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SeckillGoodsActivity extends BaseActivity {
    private List<SeckillGoodsListModel.ResultDTO.RecordsDTO> datas;
    private RecyclerView rcGoods;
    private SeckillGoodsAdapter goodsAdapter;
    private LinearLayout llNodata;
    private SmartRefreshLayout refresh;
    private int currentPage=1;
    private int count=0;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, SeckillGoodsActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.goods_type_fragment;
    }

    @Override
    protected void initView() {
        setTitleText("秒杀商品");
        rcGoods=findViewById(R.id.rcCommon);
        llNodata=findViewById(R.id.llNodata);
        refresh=findViewById(R.id.refresh);
        setView();
        getGroupGoods();
    }

    @Override
    protected void initData() {

    }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     *
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }

    public void setView(){
        datas=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getGroupGoods();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getGroupGoods();
                    }
                }, 1000);
            }
        });
    }


    public void getGroupGoods(){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("pageNum", currentPage);
            jsonObject.put("pageSize", Constants.PAGESIZE);//
            jsonObject.put("lngStr","113.784208,34.758762");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(getContext()).doPost(UrlConstants.getSeckillCommodityList, "",jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), SeckillGoodsListModel.class);
                        if (obj instanceof SeckillGoodsListModel) {
                            SeckillGoodsListModel model = (SeckillGoodsListModel) obj;
                            if (currentPage == 1) {
                                datas.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    datas=model.getResult().getRecords();
                                    llNodata.setVisibility(View.GONE);
                                    rcGoods.setVisibility(View.VISIBLE);
                                    goodsAdapter=new SeckillGoodsAdapter(datas);
                                    rcGoods.setLayoutManager(new GridLayoutManager(SeckillGoodsActivity.this,2,RecyclerView.VERTICAL,false));
                                    rcGoods.setAdapter(goodsAdapter);
                                    goodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            SeckillGoodsDetail.actionStart(SeckillGoodsActivity.this,datas.get(position).getId());
                                        }
                                    });
                                    if (goodsAdapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                } else {
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                    rcGoods.setVisibility(View.GONE);
                                }
                            } else {
                                datas.addAll(model.getResult().getRecords());
                                goodsAdapter.notifyDataSetChanged();
                                if (goodsAdapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishRefresh();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishRefreshWithNoMoreData();
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}
